I cannot run my migration command due to this error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
user_schoolsadd constraintuser_schools_school_id_foreignforeign key (school_id) referencesschools(id) on delete cascade)
users
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->softDeletes('deleted_at', 0);
$table->timestamps();
});
schools
Schema::create('schools', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('code')->unique();
$table->string('name');
$table->set('type', ['TK', 'SD', 'SMP', 'SMA', 'SMK']);
$table->softDeletes('deleted_at', 0);
$table->timestamps();
});
user_schools
Schema::create('user_schools', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('school_id')->constrained('schools')->onDelete('cascade');
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->set('type', ['Manager', 'Staff', 'Teacher', 'Student']);
$table->softDeletes('deleted_at', 0);
$table->timestamps();
});
NOTE: My migration files are based on laravel documentation yet I'm getting this error.
Any idea?
The problem is that the types for your primary and foreign key columns don't match.
Your primary key columns are UUID and your foreign key columns are BIGINT.
Changing the following should solve the error:
$table->foreignId('school_id')->constrained('schools')->onDelete('cascade');
to
$table->uuid('school_id')->constrained('schools')->onDelete('cascade');